package me.huha.util;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.apache.log4j.Logger;

/**
 *	     类名: IpUtils.java
 *    描述: Ip相关性的工具
 *    作者: Yepx
 * 创建日期: 2017年2月13日 下午5:34:25
 */
public class IpUtils {

	private static Logger logger = Logger.getLogger(IpUtils.class);
    
	//枚举类型定义 ip类型
	public enum IpType {
		ipv4("IPV4", 1), ipv6("IPV6", 2);

		/**
		 * 接口名
		 */
		private String name;

		/**
		 * 下标
		 */
		private Integer index;

		/**
		 * 
		 * @param name
		 * @param index
		 */
		private IpType(String name, Integer index) {
			this.name = name;
			this.index = index;
		}

		/**
		 * 根据下表获取名称
		 * 
		 * @param index
		 * @return
		 */
		public static String getName(int index) {
			for (IpType c : IpType.values()) {
				if (c.getIndex() == index) {
					return c.name;
				}
			}
			return null;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public Integer getIndex() {
			return index;
		}

		public void setIndex(Integer index) {
			this.index = index;
		}

	}

	/**
	 * 判断IP类型
	 * @param ip
	 * @return
	 */
	public static IpType checkIpType(String ip) {
		InetAddress local;
		try {
			local = InetAddress.getByName(ip);
			if (local instanceof Inet6Address) {
				return IpType.ipv6;
			} else if (local instanceof Inet4Address) {
				return IpType.ipv4;
			}
		} catch (UnknownHostException e) {
			logger.info("", e);
		}
		return null;
	}

}
